<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="1">我负责的</el-menu-item>
      <el-menu-item index="3" v-if="followDetailsListMyGroup">本事业部</el-menu-item>
      <el-menu-item index="2" v-if="followDetailsListMyDept">本部门</el-menu-item>
      <el-menu-item index="0" v-if="followDetailsListAll">全部</el-menu-item>
    </el-menu>

    <div class="table-container">
      <vxe-grid ref='customerListGrid' v-bind="gridOptions"  size="mini" :loading="listLoading">
        <template #form>
          <!--搜索-->
          <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
            <el-form-item label="跟进ID：">
              <el-input v-model="listQuery.trackingId"></el-input>
            </el-form-item>
            <el-form-item label="客户编号：">
               <el-input v-model="listQuery.customerNumber"></el-input>
            </el-form-item>

            <el-form-item label="产品线：">
              <el-select v-model="listQuery.goodsLineId" class="input-width" style="width:195px" placeholder="请选择" clearable >
                <el-option :label="item.cddValue" v-for="item in goodsLineList" :value="item.cddId" :key="item.cddId"></el-option>
              </el-select>
            </el-form-item>


            <el-form-item label="跟进时间：">
              <el-date-picker
                v-model="listQuery.createTime"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="跟进人：" v-if="listQuery.tab!='1'">
              <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="item in userOptionList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="跟进方式：">
              <el-select  v-model="listQuery.trackingTypeId" placeholder="请选择" clearable @change="changeTmId" multiple >
                <el-option v-for="item in trackingMethodList"  :value="item.tmId" :label="item.trackingMethod" :key="item.tmId"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="沟通方式：">
              <el-select  v-model="listQuery.trackingMethodId" placeholder="请选择" clearable multiple >
                <el-option v-for="item in interactList"  :value="item.interactId" :label="item.interactType" :key="item.cddId"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="跟进目的：">
              <el-select  v-model="listQuery.trackingPurposeId" placeholder="请选择" clearable>
                <el-option v-for="item in purposeList"  :value="item.purposeId" :label="item.purposeTitle" :key="item.purposeId"></el-option>
                <el-option label="公司破产或已关闭" :value="0"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="跟进来源：">
              <el-select  v-model="listQuery.source" placeholder="请选择" clearable>
                <el-option value="手工新增"></el-option>
                <el-option value="销售加"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="客户创建时间：">
              <el-date-picker
                v-model="listQuery.customerCreateTime"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="客户负责时间：">
              <el-date-picker
                v-model="listQuery.myChargeTime"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>

            </el-form-item>

            <el-form-item label="字数筛选：">
              <el-select  v-model="listQuery.trackingContentLength" placeholder="请选择" clearable>
                <el-option value="0,10" label="10 字以内"></el-option>
                <el-option value="10,30" label="10-30 字"></el-option>
                <el-option value="30,50" label="30-50 字"></el-option>
                <el-option value="50,100" label="50-100 字"></el-option>
                <el-option value="100,10000" label="100 字以上"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="新老客户：">
              <el-select  v-model="listQuery.dealCustomerType " placeholder="请选择" clearable>
                <el-option value="new" label="新客户"></el-option>
                <el-option value="old" label="老客户"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                @click="handleSearchList()"
                type="primary">
                查询
              </el-button>
              <el-button
                v-if="exportFollowDetailsListAll"
                :loading="btnloading"
                @click="downloadExcel"
                type="primary">
                导出
              </el-button>
            </el-form-item>
          </el-form>
        </template>
        <template #pager>
          <div style="overflow: hidden">
            <div class="pagination-container">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize"
                :page-sizes="[10,15,20]"
                :total="count">
              </el-pagination>
            </div>
          </div>
        </template>

        <template #toolbar_buttons>

        </template>

        <template #num1_default="{ row, rowIndex }">
          <span v-if="row.isShowCustomerName == 0 && listQuery.tab == 3"> {{row.customerNumber}}</span>
          <el-link @click="toDetail(row)" type="primary" style="white-space: normal;" v-else>
            {{row.customerNumber}}
          </el-link>
          <!--是否有权限-->
          <div v-if="row.isShowCustomerName" style="white-space: normal;">{{row.customerName}}</div>
        </template>

        <template #num2_default="{ row, rowIndex }">
          <div v-if="row.trackingPics.length>0">
            <div v-for="(item,index) in row.trackingPics" :key="index" :class="{imgStyle:checkFileType(item)=='image'}">
              <!-- 音频 -->
              <div v-if="checkFileType(item)=='audio'">
                <audio controls style="width: 220px; height: 30px">
                  <source :src="item" type="audio/mpeg" />
                  <source :src="item" type="audio/ogg" />
                  <source :src="item" type="audio/mp3" />
                  您的浏览器不支持该音频格式。
                </audio>
              </div>
              <!-- 图片 -->
              <div v-else-if="checkFileType(item)=='image'" style="width: 40px;margin-right:10px">
                <el-image
                  style="width: 40px; height: 40px;"
                  :src="item"
                  :preview-src-list="Array(item)">
                </el-image>
              </div>
              <div v-else>
                <div>{{ item }}</div>
              </div>
            </div>
          </div>
        </template>
        <template #num_sum="{ row, rowIndex }">
           {{row.trackingContent.length}}
        </template>

        <template #num4_default="{ row, rowIndex }">
          <el-button
            type="text"
            size="mini"
            @click="showGj(row,'edit')">编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="delItme(row)">删除
          </el-button>
          <el-button
            v-if="listQuery.tab !=1 && addSaleWorkOrder"
            type="text"
            size="mini"
            @click="workOrder(row)">发布工单
          </el-button>
        </template>
      </vxe-grid>
    </div>

     <!--编辑跟进-->
    <addGj ref="addGj" @getList="getList"></addGj>

    <!-- 发布工单 -->
    <addWorkOrder ref="addWorkOrder"></addWorkOrder>

  </div>
</template>
<script>
import {
  getCustomerOption,
  getOrderUsersList,
  getCustomerSetting
} from '@/api/partner'
import {
  delTracking
} from '@/api/company'
import {
  getPurposeListAPI,
  getTrackingMethodListAPI,
  getInteractListAPI,
  getTrackDetailListAPI
} from '@/api/fms'
import {formatDate} from '@/utils/date';
import store from '@/store'
import addGj  from './components/addGj.vue'
import "@/utils/jQuery.print"
import addWorkOrder from '@/views/components/addWorkOrder';
import { mapGetters } from 'vuex'
const defaultListQuery={
  tab:'1',
  pageNum: 1,
  pageSize: 10,
  customerId: '',//客户名称
  goodsLineId:'',//产品线名称
  createTime: [],//跟进时间
  userId:'',//跟进人id
  trackingTypeId:[],//跟进方式
  trackingMethodId: [],//客户沟通方式
  trackingPurposeId: '',//跟进目的
  source:'',//来源
  customerCreateTime:[],
  myChargeTime:[],
  customerNumber:'',
  trackingContentLength:'',
  dealCustomerType:'',
  trackingId:''
};

export default {
  name: "followDetailsList",
  data(){
    return {
      userOptionList: [],
      goodsLineList: [],
      trackingMethodList: [],
      interactList: [],
      purposeList: [],
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      count: 0,
      listLoading: false,
      roles: store.getters.roles ? store.getters.roles : [],
      customerName:'',
      btnloading:false,
      gridOptions:{
        border: true,
        id: 'trackingId',
        align:'center',
        rowConfig: {
          keyField: 'trackingId',
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          },
          className:'mytoolbar',
        },
        columns: [
          {
            field: 'customerNumber',
            title: '客户编号',
            width: 200,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'goodsLineNames',
            title: '产品线',
            width: 150,
          },
          {
            field: 'stepName',
            title: '开发阶段',
            width: 100
          },
          {
            field: 'dealCustomerType',
            title: '新老客户',
            width: 100
          },
          {
            field: 'createTime',
            title: '跟进时间',
            width: 100,
          },
          {
            field: 'userName',
            title: '跟进人',
            width: 100,
          },
          {
            field: 'departmentName',
            title: '事业部',
            width: 100,
          },
          {
            field: 'trackingTypeValue',
            title: '跟进方式',
            width: 100,
          },
          {
            field: 'trackingMethodValue',
            title: '沟通方式',
            width: 100,
          },
          {
            field: 'trackingPurposeValue',
            title: '跟进目的',
            width: 100,
          },
          {
            field: 'trackingContent',
            title: '跟进内容',
            width: 200,
          },
          {
            field: 'trackingContentLength',
            title: '字数统计',
            width: 100,
            slots: {
              default: 'num_sum',
            },
          },
          {
            field: 'trackingPics',
            title: '附件',
            width: 250,
            slots: {
              default: 'num2_default',
            },
          },
          {
            field: 'nextTrackingTime',
            title: '下次跟进时间',
            width: 150,
          },
          {
            field: 'source',
            title: '跟进来源',
            width: 100,
          },
          {
            field: '',
            title: '操作',
            width: 220,
            fixed:'right',
            slots: {
              default: 'num4_default',
            },
          },
        ],
        data:[],
      },
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    followDetailsListMyDept (){
      if(this.roles.indexOf("followDetailsListMyDept") != -1){
        return true
      }else{
        return false
      }
    },
    followDetailsListAll() {
      if(this.roles.indexOf("followDetailsListAll") != -1){
        return true
      }else{
        return false
      }
    },
    exportFollowDetailsListAll(){
      if(this.roles.indexOf("exportFollowDetailsListAll") != -1){
        return true
      }else{
        return false
      }
    },
    followDetailsListMyGroup(){
      if(this.roles.indexOf("followDetailsListMyGroup") != -1){
        return true
      }else{
        return false
      }
    },
    addSaleWorkOrder(){
      if(this.roles.indexOf("addSaleWorkOrder") != -1){
        return true
      }else{
        return false
      }
    },
  },
  created() {
    if(this.$route.query.tab){
      this.listQuery.tab = this.$route.query.tab
    }
    if(this.$route.query.trackingId){
      this.listQuery.trackingId = this.$route.query.trackingId
    }
    if(!this.$route.query.trackingId && !this.$route.query.tab){
      let now = new Date();
      let today = formatDate(now, "yyyy-MM-dd");
      this.listQuery.createTime = [today, today];
    }

    this.handleSearchList()
    this.getCustomerSettingList()
    this.getUserOptionListData()
    this.getTrackingMethodList()
    this.getInteractList()
    this.getPurposeList()
  },
  filters: {
    fifApply(val){
      if(val == 0){
        return '待提交'
      }else if(val == 10){
         return '未审核'
      }else if(val == 20){
        return '审核未通过'
      }
    },
  },
  components : {
    addGj,addWorkOrder
  },
  mounted() {
  },
  methods: {
    //提交工单
    workOrder(row){
      this.$refs.addWorkOrder.showPop('trackingId',row.trackingId,row.customerName,row.userName)
    },
    //下载excle
    downloadExcel(){
      let params
      params = JSON.parse(JSON.stringify(this.listQuery));
      params.isExport = 1;
      delete params.pageSize;
      delete params.pageNum;
      this.btnloading = true
      getTrackDetailListAPI(params).then((res)=>{
        this.btnloading = false;
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(()=>{
        this.btnloading = false;
      })
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    openWord(item) {
      window.open(item)
    },
     // 判断文件类型
    checkFileType(fileName) {
      if (fileName.match(/\.(jpg|jpeg|png|gif|webp)/)) {
        return "image";
      } else if (fileName.match(/\.(doc|docx)/)) {
        return "word";
      } else if (fileName.match(/\.(wav|mp3|aac|ogg|wma)/)) {
        return "audio";
      } else {
        return "unknown";
      }
    },
    // 删除跟进
    delItme(item){
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delTracking({ trackingId: item.trackingId }).then((res) => {
          this.$message({
            type: 'success',
            message: '已删除成功!'
          });
          this.getList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //编辑跟进
    showGj(item, type) {
      this.$refs.addGj.showTracking(item,type)
    },
    //获取产品线配置
    getCustomerSettingList(){
      getCustomerSetting().then((res)=>{
        res.forEach((el)=>{
         if(el.cdtCode == 'goods_line'){
            this.goodsLineList = el.data
          }
        });
      })
    },

    //获取跟进方式
    getTrackingMethodList(){
      getTrackingMethodListAPI({pageNum:1,pageSize: 1000,isEnable:1}).then((res)=>{
        this.trackingMethodList = res.list
      })
    },
    //切换跟进方式，变化沟通方式
    changeTmId(){
      this.interactList = [];
      this.listQuery.trackingMethodId = '';
      if(this.listQuery.trackingTypeId){
        this.getInteractList();
      }
    },

    //获取沟通方式
    getInteractList(){
      getInteractListAPI({pageNum:1,pageSize: 1000,isEnable:1,tmId:this.listQuery.trackingTypeId}).then((res)=>{
        this.interactList = res.list
      })
    },

    //获取员工下拉选项
    getUserOptionListData(){
      getOrderUsersList({type:'sale'}).then((res)=>{
        this.userOptionList = res;
      })
    },

    //跟进目的列表
    getPurposeList(){
      getPurposeListAPI({pageNum:1,pageSize: 1000,isEnable:1,stepId:'',sort:'asc'}).then((res)=>{
        this.purposeList = res.list
      })
    },

    //去客户详情页
    toDetail(item){
      let routeData = this.$router.resolve({name:'customerDetail',query:{id:item.customerId}});
      window.open(routeData.href);
    },

    //客户名称输入匹配
    querySearch(queryString, cb){
      getCustomerOption({keywords:queryString}).then((res)=>{
        cb(res);
      })
    },

    //选择客户名称
    handleSelectCustomerName(item) {
      this.customerName=item.customerName
      this.listQuery.customerId = item.customerId;
    },
    clearInput() {
      this.customerName = '';
      this.listQuery.customerId = '';
    },

    handleSelect(key) {
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
      this.listQuery.tab = key;
      let now = new Date();
      let today = formatDate(now, "yyyy-MM-dd");
      this.listQuery.createTime = [today, today];
      this.handleSearchList()
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      this.gridOptions.data = [];
      getTrackDetailListAPI(this.listQuery).then(response => {
        this.gridOptions.data = response.list;
        this.count = response.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },
  },
}
</script>
<style scoped>
.imgStyle{
  float: left;
}

</style>



